#include "TabBarWidget.h"
#include <QPainter>
#include <QVBoxLayout>

TabBarWidget::TabBarWidget(QWidget *parent)
	:QWidget(parent)
{
	m_index = 0;
}

void TabBarWidget::paintEvent(QPaintEvent *event)
{
	QPainter painter(this);
	if(m_btnList.size() == 0)
		return;

	int l = m_btnList[m_index]->geometry().left() - 1;
	int r = m_btnList[m_index]->geometry().right();

	int y = height() - 1;
	painter.setPen(QColor(224,224,224));
	painter.drawLine(0,y,l,y);
	painter.drawLine(r,y,width(),y);
}

void TabBarWidget::onBtnClicked()
{
	int idx = m_btnList.indexOf((QPushButton*)sender());
	if(idx != m_index)
	{
		m_index = idx;
		emit currentIndexChanged(m_index);
		updateTabStyle();
		update();
	}
}

int TabBarWidget::currentIndex()
{
	return m_index;
}

void TabBarWidget::setCurrentIndex(int index)
{
	m_index = index;
}

void TabBarWidget::addTab(QString text)
{
	QVBoxLayout *l = (QVBoxLayout*)layout();
	QPushButton *btn = new QPushButton(text);
	btn->setFixedSize(96,this->height());
	l->insertWidget(m_btnList.size(),btn);

	connect(btn,SIGNAL(clicked()),this,SLOT(onBtnClicked()));
	m_btnList.push_back(btn);
}

void TabBarWidget::updateTabStyle()
{
	for(int i = 0; i < m_btnList.size(); i++)
	{
		QString style = "border-top: 1px solid rgb(224,224,224);\n";
		style += "border-right: 1px solid rgb(224,224,224);\n";
		if(i == 0)
		{			
			style += "border-top-left-radius: 5;\n";
			style += "border-left: 1px solid rgb(224,224,224);\n";			
		}
		if(i == m_btnList.size() - 1)
			style += "border-top-right-radius: 5;\n";		
		if(i == m_index)
			style += "color:rgb(51,76,103);";
		else
			style += "color:rgb(102,102,102);";
		
		m_btnList[i]->setStyleSheet(style);
	}
}